import ButtonGroup, { Button } from "@/components/ButtonGroup";
import { View } from "@tarojs/components";
import styles from "./index.scss";
import { Form } from "@nutui/nutui-react-taro";
import Input from "@/components/Input";
import Taro, { showToast } from "@tarojs/taro";
import Upload from "@/components/Upload";

import { useFamilyStore } from "@/model";
import { updateUserInfo } from "@/services/User";
import { useEffect } from "react";
import InputPassword from "@/components/Input/InputPassword";
import { getUserInfo, setUserInfo } from "@/utils/token";
import RadioGroup from "@/components/Form/RadioGroup";
import { GenderEnum } from "@/constants/enum";
import { enumConvertOption } from "@/utils";

export default () => {
  const [form] = Form.useForm();
  const info = getUserInfo();
  useEffect(() => {
    form.setFieldsValue({
      ...info,
      avatar: info?.avatar?[info.avatar]:undefined,
    });
  }, []);

  return (
    <View className={styles.container}>
      <View className={styles.formBox}>
        <Form
          starPosition="left"
          className={styles.form}
          form={form}
          onFinish={async (v) => {
            const newInfo = {
              id: info?.id,
              gender: v.gender,
              nickname: v.nickname,
            };
            if (v?.avatar) {
              newInfo.avatar = v?.avatar[0];
            }
            if (v?.newPassword) {
              newInfo.password = v?.newPassword;
            }
            await updateUserInfo(newInfo);
            setUserInfo({
                ...info,
                ...newInfo,
            })
            showToast({
              title: "修改成功",
              icon: "none",
              mask: true,
              duration: 1000,
              success: () => {
                setTimeout(() => {
                  Taro.navigateBack();
                }, 1000);
              },
            });
          }}
        >
          <Form.Item label="头像" name="avatar">
            <Upload maxCount={1} />
          </Form.Item>
          <Form.Item
            label="昵称"
            name="nickname"
            rules={[
              {
                required: true,
                message: "请输入",
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="性别" name="gender">
            <RadioGroup
              options={enumConvertOption(GenderEnum)}
              multiple={false}
            />
          </Form.Item>
          <Form.Item label="新密码" name="newPassword">
            <InputPassword />
          </Form.Item>
        </Form>
      </View>

      <ButtonGroup>
        <Button
          onClick={() => {
            Taro.navigateBack();
          }}
        >
          取消
        </Button>
        <Button type="primary" onClick={() => form.submit()}>
          确认
        </Button>
      </ButtonGroup>
    </View>
  );
};
